//
//  UIView+HUDExtension.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/1.
//

import UIKit
import AttributedString
import Toast_Swift
import JKSwiftExtension
import MBProgressHUD

extension UIView: ARPOPCompatible {}
extension ARPOP where Base: UIView {
    
    /// 展示loading
    /// - Parameter duration: 时长 default：0
    /// - Parameter message: 消息
    func showLoading(duration: TimeInterval = 0, message: String? = nil) {
        
        self.hideHUD()
        
        let loadingView = UIImageView.init(image: .init(named: "hud_loading"))
        let animation = CABasicAnimation(keyPath: "transform.rotation.z")
        animation.toValue = Double.pi * 2.0
        animation.duration = 1
        animation.isCumulative = true
        animation.repeatCount = Float.infinity
        animation.isRemovedOnCompletion = false
        loadingView.layer.add(animation, forKey: "rotationAnimation")
        
        let customView = ARCustomHUD(titleText: message, customView: loadingView)
        customView.backgroundColor = .black.withAlphaComponent(0.9)
        customView.sizeToFit()
        
        let hud: MBProgressHUD = MBProgressHUD.showAdded(to: self.base, animated: true)
        hud.customView = customView
        hud.margin = 0
        hud.mode = .customView
        hud.bezelView.style = .solidColor
        hud.bezelView.backgroundColor = .clear
        hud.removeFromSuperViewOnHide = true
        
        if duration > 0 {
            hud.hide(animated: true, afterDelay: duration)
        }
    }
    
    /// 展示toast
    func makeToast(_ msg: String) {
        self.base.makeToast(msg, position: .center)
    }
    
    /// 隐藏
    func hideHUD() {
        self.base.hideAllToasts()
        MBProgressHUD.hide(for: self.base, animated: true)
    }
    
}

// MARK: -

/// CustomHUD
fileprivate class ARCustomHUD: UIView {
    
    var customSize: CGSize = .zero
    let customView: UIView?
    let titleLabel: UILabel?
    let titleText: NSAttributedString?
    
    init(titleText: String?, customView: UIView?) {
        
        self.customView = customView
        if let titleText = titleText, titleText.isEmpty == false {
            let label = UILabel(frame: .zero)
            label.numberOfLines = 0
            label.textAlignment = .center
            self.titleLabel = label
            self.titleText = ASAttributedString.init(string: titleText, .font(ARHelper.font(14, weight: .regular)), .foreground(.white), .paragraph(.alignment(.center), .lineSpacing(5))).value
        } else {
            self.titleText = nil
            self.titleLabel = nil
        }
        
        super.init(frame: .zero)
        
        // setupUI
        self.setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
//        self.backgroundColor = .black.withAlphaComponent(0.8)
//        self.layer.cornerRadius = 8
        
        // 宽度由text来决定，高度共同决定
        let maxWidth: CGFloat = 285
        // view 和 label 之间的margin
        let margin: CGFloat = 12
        // 外围的padding
        let padding: CGFloat = 15
        
        var width: CGFloat = 0
        var height: CGFloat = 0
        
        let hasCustomView = customView == nil ? false : true
        let hasTitle = titleText == nil ? false : true
        
        if !hasTitle && !hasCustomView {
            fatalError("customView and titleText is nil")
        }
        
        if let customView = customView, !hasTitle {
            // 单独的customView
            self.addSubview(customView)
            
            let viewWidth = customView.frame.width > 0 ? customView.frame.width : 40
            let viewHeight = customView.frame.height > 0 ? customView.frame.height : 40
            
            width = viewWidth * 2
            height = width
            
            customView.frame = .init(x: (width - viewWidth) * 0.5, y: (height - viewHeight) * 0.5, width: viewWidth, height: viewHeight)
            self.customSize = .init(width: width, height: height)
            return
        }
        
        if var titleLabel = titleLabel, !hasCustomView {
            // 单独的titleLabel
            self.addSubview(titleLabel)
            titleLabel.attributedText = titleText
            titleLabel.jk.width = maxWidth
            titleLabel.sizeToFit()
            
            width = titleLabel.jk.width + padding * 2
            height = titleLabel.jk.height + padding * 2
            titleLabel.frame = .init(x: (width - titleLabel.jk.width) * 0.5, y: (height - titleLabel.jk.height) * 0.5, width: titleLabel.jk.width, height: titleLabel.jk.height)
            self.customSize = .init(width: width, height: height)
            return
        }
        
        if var titleLabel = titleLabel, let customView = customView {
            self.addSubview(customView)
            
            let viewWidth = customView.frame.width > 0 ? customView.frame.width : 40
            let viewHeight = customView.frame.height > 0 ? customView.frame.height : 40
            
            self.addSubview(titleLabel)
            titleLabel.attributedText = titleText
            titleLabel.jk.width = maxWidth
            titleLabel.sizeToFit()
            
            width = titleLabel.jk.width + padding * 2
            height = viewHeight + margin + titleLabel.jk.height + padding * 2
            
            customView.frame = .init(x: (width - viewWidth) * 0.5, y: padding, width: viewWidth, height: viewHeight)
            titleLabel.frame = .init(x: padding, y: customView.frame.maxY + margin, width: titleLabel.jk.width, height: titleLabel.jk.height)
            self.customSize = .init(width: width, height: height)
            return
        }
    }
    
    override var intrinsicContentSize: CGSize {
        self.customSize
    }
    
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        return self.intrinsicContentSize
    }
}
